package org.jeecg.modules.websocket.manager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author by sean
 * @desc: WebSocketSession分组
 * @since 2024-10-17 星期四 15:50:41
 */
@Slf4j
public class WebSocketSessionGroup {

    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public void addSession(String key, WebSocketSession session) {
        sessions.put(key, session);
    }

    public WebSocketSession getSession(String key) {
        return sessions.get(key);
    }

    public WebSocketSession removeSession(String key) {
        return sessions.remove(key);
    }

    /**
     * 删除并同步关闭连接
     *
     * @param key
     */
    public void removeAndClose(String key) {
        WebSocketSession session = this.removeSession(key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isEmpty() {
        return sessions.isEmpty();
    }

    public void sendMessage(TextMessage textMessage) {
        sessions.forEach((key, session)->{
            if (session.isOpen()) { // 检查会话是否打开
                try {
                    synchronized (session){
                        session.sendMessage(textMessage); // 发送消息
                    }
                } catch (Exception e) {
                    e.printStackTrace(); // 处理异常
                    // 可以选择从 sessions 中移除失效的会话
                     removeAndClose(key);
                }
            }
        });
    }


}
